package com.aidex.biz.controller;

import java.util.List;
import java.util.UUID;

import com.aidex.biz.domain.CustomerDongtai;
import com.aidex.biz.domain.Xiezu;
import com.aidex.biz.service.CustomerDongtaiService;
import com.aidex.biz.service.XiezuService;
import com.aidex.common.annotation.Log;
import com.aidex.common.core.domain.R;
import com.aidex.common.core.domain.entity.SysUser;
import com.aidex.common.utils.StringUtils;
import com.aidex.common.utils.sign.Md5Utils;
import com.aidex.framework.websocket.WebSocketUsers;
import com.aidex.system.service.ISysUserService;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.aidex.common.core.page.PageDomain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.aidex.common.enums.BusinessType;
import com.aidex.common.utils.poi.ExcelUtil;
import javax.validation.constraints.*;
import org.springframework.web.bind.annotation.*;
import com.aidex.common.core.controller.BaseController;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import com.aidex.biz.domain.CustomerXiezu;
import com.aidex.biz.service.CustomerXiezuService;
import com.aidex.common.utils.SecurityUtils;

/**
 * 客户协助Controller
 * @author sean
 * @email 2074844820@qq.com
 * @date 2023-11-29
 */
@RestController
@RequestMapping("/biz/bizCustomerXiezu")
public class CustomerXiezuController extends BaseController
{
    @Autowired
    private CustomerXiezuService customerXiezuService;
    @Autowired
    private XiezuService xiezuService;
    @Autowired
    private CustomerDongtaiService customerDongtaiService;
    @Autowired
    private ISysUserService iSysUserService;

    /**
     * 查询客户协助列表
     */
    @GetMapping("/list")
    public R<PageInfo> list(CustomerXiezu customerXiezu, HttpServletRequest request, HttpServletResponse response)
    {
        if(SecurityUtils.isAdmin(SecurityUtils.getUserId())){
                customerXiezu.setCompanyId(null);
        }else{
                     customerXiezu.setCompanyId(SecurityUtils.getLoginUser().getUser().getCompanyId());
                 }
        customerXiezu.setPage(new PageDomain(request, response));
        return R.data(customerXiezuService.findPage(customerXiezu));
    }

    /**
     * 查询我的协助列表
     */
    @GetMapping("/myXiezulist")
    public R<PageInfo> myXiezulist(CustomerXiezu customerXiezu, HttpServletRequest request, HttpServletResponse response)
    {

            customerXiezu.setUserId(SecurityUtils.getLoginUser().getUserId());

        customerXiezu.setPage(new PageDomain(request, response));
        return R.data(customerXiezuService.findMyXieZuList(customerXiezu));
    }

    /**
     * 获取客户协助详细信息
     */
    @GetMapping(value = "/{id}")
    public R<CustomerXiezu> detail(@PathVariable("id") String id)
    {
        return R.data(customerXiezuService.get(id));
    }

    /**
     * 新增客户协助
     */
    @Log(title = "客户协助", businessType = BusinessType.INSERT)
    @PostMapping
    public R add(@RequestBody @Validated  CustomerXiezu customerXiezu)
    {
        if(customerXiezu.getXiezuUsers().length==0){
            return R.fail("请选择用户");
        }
        // 添加协助员工
        for(String userid:customerXiezu.getXiezuUsers()){
            customerXiezu.setId(Md5Utils.hash(userid+customerXiezu.getCustomerId()));
            customerXiezu.setIsNewRecord();
            customerXiezu.setXiezuUserId(userid);
            if(null==customerXiezuService.get(Md5Utils.hash(userid+customerXiezu.getCustomerId()))){
                try{
                    customerXiezuService.save(customerXiezu);
                }catch (Exception e){
                    logger.info("协助人员添加失败"+e.getMessage());
                }
            }
            JSONObject jsonObject=new JSONObject();
            jsonObject.put("type","xiezuCus");
            jsonObject.put("msg","您有新同事协助信息");
            WebSocketUsers.sendMessageToUserByText(WebSocketUsers.TYPE_PC,
                    userid, jsonObject.toJSONString());
        }
        // 添加协助信息
        String userids="",userNames="";
        for(int i=0;i< customerXiezu.getXiezuUsers().length;i++){
            if(i==customerXiezu.getXiezuUsers().length-1){
                userids+=customerXiezu.getXiezuUsers()[i];
                userNames+=customerXiezu.getXiezuUserNames()[i];
            }else {
                userids+=customerXiezu.getXiezuUsers()[i]+",";
                userNames+=customerXiezu.getXiezuUserNames()[i]+",";
            }
        }

        CustomerDongtai customerDongtai=new CustomerDongtai();
        customerDongtai.setCustomerId(customerXiezu.getCustomerId());
        customerDongtai.setType("2");
        customerDongtai.setContent(SecurityUtils.getLoginUser().getUser().getName()+"-添加协助客户-"+userNames);
        customerDongtaiService.save(customerDongtai);


        Xiezu xiezu=new Xiezu();
        xiezu.setXiezuUserIds(userids);
        xiezu.setXiezuUserNames(userNames);
        xiezu.setCustomerId(customerXiezu.getCustomerId());
        xiezuService.save(xiezu);
        return R.status(true);
    }

    /**
     * 修改客户协助
     */
    @Log(title = "客户协助", businessType = BusinessType.UPDATE)
    @PutMapping
    public R edit(@RequestBody @Validated CustomerXiezu customerXiezu)
    {
        return R.status(customerXiezuService.save(customerXiezu));
    }


    /**
     * 删除客户协助
     */
    @Log(title = "客户协助", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R remove(@PathVariable String[] ids)
    {
        if(ids.length==1){
            CustomerXiezu customerXiezu=customerXiezuService.get(ids[0]);
            if(null!=customerXiezu){
                SysUser sysUser=iSysUserService.get(customerXiezu.getXiezuUserId());
                if(customerXiezuService.deleteCustomerXiezuByIds(ids)>0){
                    CustomerDongtai customerDongtai=new CustomerDongtai();
                    customerDongtai.setCustomerId(customerXiezu.getCustomerId());
                    customerDongtai.setType("2");
                    customerDongtai.setContent(SecurityUtils.getLoginUser().getUser().getName()+"-删除协助人员-"+sysUser.getName()+("0".equals(sysUser.getStatus())?"(在职)":"(离职)"));
                    return R.status(customerDongtaiService.save(customerDongtai));
                }
            }

        }
        return R.fail("操作失败！");
    }

    /**
     * 获取最大编号
     */
    @GetMapping("/findMaxSort")
    public R findMaxSort()
    {
        return R.data(customerXiezuService.findMaxSort(new CustomerXiezu()));
    }

    /**
     * 导出客户协助列表
     */
    @Log(title = "客户协助", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public R export(CustomerXiezu customerXiezu)
    {

            if(SecurityUtils.isAdmin(SecurityUtils.getUserId())){
                    customerXiezu.setCompanyId(null);
            }else{
                         customerXiezu.setCompanyId(SecurityUtils.getLoginUser().getUser().getCompanyId());
                     }
        List<CustomerXiezu> list = customerXiezuService.findList(customerXiezu);
        ExcelUtil<CustomerXiezu> util = new ExcelUtil<CustomerXiezu>(CustomerXiezu.class);
        return util.exportExcel(list, "客户协助数据");
    }

}
